<template>
  <div class="smart-recommendations">
    <div class="section-header">
      <h2>智能匹配推荐</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="generateRecommendations">重新生成</el-button>
        <el-button type="info" @click="toggleDebug">显示/隐藏调试信息</el-button>
      </div>
    </div>
    
    <div v-loading="loading">
      <div v-if="!recommendations.length" class="empty-state">
        <el-empty description="暂无推荐，请先完善个人资料" />
      </div>
      <div v-else>
        <div class="recommendations-grid">
          <div v-for="rec in recommendations" :key="rec.recordId" class="recommendation-card">
            <div class="rec-header">
                <div class="rec-logo">
                  <!-- 尝试直接使用模拟的logo，测试是否是字段问题 -->
                  <img :src="getLogoUrl(rec)" :alt="rec.clubName || rec.associationName" />
                </div>
              <div class="rec-info">
                <h4>{{ rec.clubName || rec.associationName }}</h4>
                <p>{{ rec.recruitmentTitle }}</p>
                <el-tag :type="getTypeStyle(rec.clubType)" size="small">
                  {{ getTypeName(rec.clubType) }}
                </el-tag>
              </div>
              <div class="match-score">
                <div class="score-circle">
                  <span class="score-number">{{ rec.matchScore }}</span>
                  <span class="score-label">分</span>
                </div>
                <p class="score-desc">匹配度</p>
              </div>
            </div>
            
            <div class="rec-details">
              <h5>评分详情</h5>
              <div class="score-breakdown">
                <div class="score-item">
                  <span>专业匹配</span>
                  <el-progress :percentage="getScoreValue(rec, ['skillMatchScore', 'skillScore', 'majorMatchScore'])" :show-text="false" />
                  <span>{{ getScoreValue(rec, ['skillMatchScore', 'skillScore', 'majorMatchScore']) }}分</span>
                </div>
                <div class="score-item">
                  <span>兴趣匹配</span>
                  <el-progress :percentage="getScoreValue(rec, ['interestMatchScore', 'interestScore'])" :show-text="false" />
                  <span>{{ getScoreValue(rec, ['interestMatchScore', 'interestScore']) }}分</span>
                </div>
                <div class="score-item">
                  <span>其他因素</span>
                  <el-progress :percentage="getScoreValue(rec, ['otherFactorsScore', 'otherScore'])" :show-text="false" />
                  <span>{{ getScoreValue(rec, ['otherFactorsScore', 'otherScore']) }}分</span>
                </div>
                <div class="score-item">
                  <span>时间匹配</span>
                  <el-progress :percentage="getScoreValue(rec, ['timeMatchScore', 'timeScore'])" :show-text="false" />
                  <span>{{ getScoreValue(rec, ['timeMatchScore', 'timeScore']) }}分</span>
                </div>
              </div>
            </div>
            
            <div class="rec-recommendation">
              <h5>推荐理由</h5>
              <p>{{ rec.recommendation || '该社团与您的兴趣和能力高度匹配' }}</p>
            </div>
            
            <div class="rec-actions">
              <el-button size="small" @click="viewClubFromRecommendation(rec)">查看详情</el-button>
              <el-button type="primary" size="small" @click="applyFromRecommendation(rec)">立即申请</el-button>
            </div>
          </div>
        </div>
        
        <!-- 调试信息面板 -->
        <div v-if="debugMode" class="debug-panel">
          <h3>调试信息</h3>
          <div v-if="recommendations.length > 0">
            <h4>第一条推荐数据结构：</h4>
            <pre>{{ JSON.stringify(recommendations[0], null, 2) }}</pre>
            <h4>所有可能的logo字段：</h4>
            <div v-for="field in possibleLogoFields" :key="field" class="debug-field">
              <strong>{{ field }}:</strong> 
              <span v-if="recommendations[0][field]">
                <code>{{ recommendations[0][field] }}</code>
              </span>
              <span v-else class="text-muted">未定义</span>
            </div>
            <h4>实际使用的logo URL：</h4>
            <pre><code>{{ getLogoUrl(recommendations[0]) }}</code></pre>
            <img 
              :src="getLogoUrl(recommendations[0])" 
              alt="Logo Preview" 
              style="max-width: 100px; max-height: 100px; margin-top: 10px; border: 1px solid #ddd;"
            />
          </div>
          <p v-else>暂无推荐数据</p>
        </div>
      </div>
    </div>
    
    <!-- 社团详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      :title="selectedClub ? (selectedClub.clubName || selectedClub.associationName) : '社团详情'" 
      width="800px"
      class="club-detail-dialog"
    >
      <div v-if="selectedClub" class="club-detail">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="club-detail-logo">
              <img :src="getLogoUrl(selectedClub)" :alt="selectedClub.clubName || selectedClub.associationName" />
            </div>
          </el-col>
          <el-col :span="16">
            <div class="club-detail-info">
              <h3>{{ selectedClub.clubName || selectedClub.associationName }}</h3>
              <p><strong>社团类型：</strong>{{ getTypeName(selectedClub.clubType) }}</p>
              <p><strong>社团简介：</strong>{{ selectedClub.description || '暂无简介' }}</p>
              <p><strong>匹配度：</strong>{{ selectedClub.matchScore || 0 }}分</p>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import smartRecommendationsApi from '@/api/campus/student/smartRecommendations'
import useUserStore from '@/store/modules/user'

// 使用解构赋值从默认导出中获取函数
const { 
  getStudentMatches,
  generateRecommendation
} = smartRecommendationsApi

// Props
const props = defineProps({
  currentUserId: {
    type: String,
    required: false,
    default: ''
  }
})

// Data
const router = useRouter()
const loading = ref(false)
const recommendations = ref([])
const detailVisible = ref(false)
const selectedClub = ref(null)
const debugMode = ref(false)
const possibleLogoFields = ['logo_url', 'clubLogoUrl', 'logoUrl', 'logo', 'club_logo', 'clubLogo', 'LogoUrl', 'LOGO_URL']

// 从多个可能的位置获取用户ID的辅助函数
const getUserIdFromStorage = () => {
  // 打印所有localStorage键值对，调试用
  console.log('===== localStorage 内容分析 =====');
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    try {
      const value = localStorage.getItem(key);
      console.log(`localStorage[${key}]:`, value);
      
      // 特别检查用户相关的关键字段
      if (key.toLowerCase().includes('user') || 
          key.toLowerCase().includes('token') || 
          key.toLowerCase().includes('auth')) {
        console.log(`🚨 可能包含用户信息的字段: ${key}`);
        // 尝试解析为对象
        try {
          const parsed = JSON.parse(value);
          console.log(`解析后内容:`, parsed);
        } catch (e) {
          console.log(`不是JSON格式`);
        }
      }
    } catch (e) {
      console.log(`读取 ${key} 时出错:`, e);
    }
  }
  console.log('==================================');

  // 尝试从所有可能的位置获取用户ID
  let userId = '';
  
  // 1. 尝试从常见的用户ID字段获取
  const userIdKeys = ['userId', 'id', 'user_id', 'username', 'loginName', 'account'];
  for (const key of userIdKeys) {
    const value = localStorage.getItem(key);
    if (value && value.trim()) {
      userId = value;
      console.log(`1. 从 ${key} 获取到用户ID:`, userId);
      break;
    }
  }
  
  // 2. 尝试从userInfo对象中获取各种可能的用户ID字段
  if (!userId) {
    try {
      const userInfoStr = localStorage.getItem('userInfo') || localStorage.getItem('userinfo');
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        console.log('发现userInfo对象:', userInfo);
        
        // 尝试所有可能的用户ID字段名
        const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'studentId'];
        for (const field of possibleIdFields) {
          if (userInfo[field] && String(userInfo[field]).trim()) {
            userId = String(userInfo[field]);
            console.log(`2. 从userInfo.${field}获取到用户ID:`, userId);
            break;
          }
        }
      }
    } catch (e) {
      console.warn('解析userInfo失败:', e);
    }
  }
  
  // 3. 尝试从token或其他认证信息中获取
  if (!userId) {
    try {
      const tokenKeys = ['token', 'Authorization', 'auth_token', 'access_token'];
      let token = '';
      
      for (const key of tokenKeys) {
        token = localStorage.getItem(key);
        if (token) break;
      }
      
      if (token) {
        console.log('发现token:', token);
        // 简单尝试解码token前半部分
        try {
          const tokenParts = token.split('.');
          if (tokenParts.length >= 2) {
            const decoded = JSON.parse(atob(tokenParts[1].replace(/-/g, '+').replace(/_/g, '/')));
            console.log('token解码内容:', decoded);
            
            // 尝试所有可能的用户ID字段名
            const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'sub', 'name'];
            for (const field of possibleIdFields) {
              if (decoded[field] && String(decoded[field]).trim()) {
                userId = String(decoded[field]);
                console.log(`3. 从token.${field}获取到用户ID:`, userId);
                break;
              }
            }
          }
        } catch (e) {
          console.warn('解码token失败:', e);
        }
      }
    } catch (e) {
      console.warn('从token获取用户ID失败:', e);
    }
  }
  
  return userId;
};

// 获取有效的用户ID（优先使用store，其次是props，最后是localStorage）
const getValidUserId = computed(() => {
  // 1. 从store获取用户ID（最高优先级）
  try {
    const userStore = useUserStore();
    if (userStore && userStore.id) {
      console.log('从store获取到用户ID:', userStore.id);
      return String(userStore.id).trim();
    }
  } catch (error) {
    console.warn('获取store用户信息失败:', error);
  }
  
  // 2. 从props获取用户ID
  const userIdFromProps = String(props.currentUserId || '').trim();
  console.log('props中的用户ID:', userIdFromProps);
  
  // 3. 从localStorage获取用户ID
  const userIdFromStorage = getUserIdFromStorage();
  const validUserId = userIdFromProps || userIdFromStorage;
  
  console.log('最终有效用户ID:', validUserId);
  return validUserId;
});

// 辅助函数：获取评分值，支持多个可能的字段名
const getScoreValue = (obj, possibleFields) => {
  if (!obj) return 0;
  
  for (const field of possibleFields) {
    if (obj[field] !== undefined && obj[field] !== null) {
      const value = Number(obj[field]);
      return isNaN(value) ? 0 : value;
    }
  }
  return 0;
};

// 辅助函数：获取社团logo URL，处理不同的字段名和默认值
const getLogoUrl = (obj) => {
  // 添加调试信息
  console.log('getLogoUrl called with:', obj);
  
  if (!obj) {
    console.log('Object is null/undefined, returning default logo');
    return '/default-club.svg';
  }
  
  // 尝试多种可能的字段名，确保包含SQL表中使用的字段
  const possibleLogoFields = ['logo_url', 'clubLogoUrl', 'logoUrl', 'logo', 'club_logo', 'clubLogo', 'LogoUrl', 'LOGO_URL'];
  
  // 遍历所有可能的字段，添加调试信息
  for (const field of possibleLogoFields) {
    const logoUrl = obj[field];
    console.log(`Checking field ${field}:`, logoUrl);
    
    if (logoUrl && logoUrl.trim() !== '') {
      console.log(`Found logo at ${field}:`, logoUrl);
      // 确保URL是有效的
      if (logoUrl.startsWith('http://') || logoUrl.startsWith('https://')) {
        return logoUrl;
      } else {
        // 对于非http/https链接，确保路径正确
        return logoUrl.startsWith('/') ? logoUrl : '/' + logoUrl;
      }
    }
  }
  
  // 如果没有找到有效的logo，返回默认图片
  console.log('No valid logo found, returning default');
  return '/default-club.svg';
};

// Methods
const loadRecommendations = async () => {
  const validUserId = getValidUserId.value;
  console.log('开始加载推荐信息，用户ID:', validUserId);
  
  if (!validUserId || validUserId === 'undefined' || validUserId === 'null' || validUserId.trim() === '') {
    console.warn('用户ID为空，无法加载推荐信息');
    ElMessage.warning('请先登录后再查看推荐信息');
    return;
  }
  
  loading.value = true;
  try {
    const response = await getStudentMatches(validUserId);
    console.log('API响应数据:', response);
    
    if (response.code === 200) {
      recommendations.value = response.data || [];
      console.log('推荐数据结构:', recommendations.value);
      
      // 如果有推荐数据，打印第一条记录的完整结构，特别是与logo相关的字段
      if (recommendations.value.length > 0) {
        console.log('第一条推荐记录详情:', recommendations.value[0]);
        console.log('检查所有可能的logo字段:');
        const firstRec = recommendations.value[0];
        const possibleLogoFields = ['logo_url', 'clubLogoUrl', 'logoUrl', 'logo', 'club_logo', 'clubLogo', 'LogoUrl', 'LOGO_URL'];
        possibleLogoFields.forEach(field => {
          console.log(`${field}:`, firstRec[field]);
        });
      }
    } else {
      console.warn('获取推荐信息失败:', response.msg);
      recommendations.value = [];
    }
  } catch (error) {
    console.error('加载推荐信息失败:', error);
    ElMessage.error('网络错误，请稍后重试');
    recommendations.value = [];
  } finally {
    loading.value = false;
  }
}

// 查看社团详情 - 修改为使用对话框显示
const viewClubFromRecommendation = (recommendation) => {
  try {
    // 直接使用推荐信息作为详情数据
    selectedClub.value = recommendation;
    detailVisible.value = true;
  } catch (error) {
    console.error('显示社团详情失败:', error);
    ElMessage.error('显示详情失败，请稍后重试');
  }
};

// 从推荐中申请 - 修改为不使用POST API，而是跳转到申请页面
const applyFromRecommendation = async (recommendation) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要申请加入「${recommendation.clubName || recommendation.associationName}」吗？`, 
      '确认申请', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const validUserId = getValidUserId.value
    if (!validUserId) {
      ElMessage.warning('请先登录后再申请')
      return
    }
    
    // 直接跳转到申请表单页面或社团浏览页面的申请功能
    // 我们这里采用跳转到社团浏览页面并显示申请对话框的方式
    ElMessage.success('请在社团详情页面中选择具体的职位进行申请')
    
    // 先显示社团详情
    viewClubFromRecommendation(recommendation)
    
    // 实际项目中可以通过路由传递参数或使用事件总线来触发申请表单
    // 这里简单处理，显示提示信息
  } catch (error) {
    // 如果是用户取消操作，不显示错误信息
    if (error !== 'cancel') {
      console.error('申请失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }
};

// 缺少的函数：获取社团类型名称
const getTypeName = (type) => {
  const typeStr = type !== null && type !== undefined ? String(type) : '';
  const map = { '1': '学术科技类', '2': '文化艺术类', '3': '体育运动类', '4': '社会实践类' };
  return map[typeStr] || '未知类型';
};

// 获取社团类型对应的样式
const getTypeStyle = (type) => {
  const typeStr = type !== null && type !== undefined ? String(type) : '';
  const map = { '1': 'primary', '2': 'success', '3': 'warning', '4': 'info' };
  return map[typeStr] || 'info'; // 使用'info'替代'default'作为默认值
};

// 切换调试模式
const toggleDebug = () => {
  debugMode.value = !debugMode.value;
}

const refreshRecommendations = () => {
  loadRecommendations();
  ElMessage.success('推荐信息已刷新');
}

const generateRecommendations = async () => {
  // 使用统一的用户ID获取方式
  const validUserId = getValidUserId.value;
  
  if (!validUserId || validUserId === 'undefined' || validUserId === 'null' || validUserId.trim() === '') {
    ElMessage.warning('请先登录后再生成推荐');
    return;
  }
  
  loading.value = true;
  try {
    // 调用生成推荐的API
    const generateResponse = await generateRecommendation({ studentId: validUserId });
    
    if (generateResponse.code === 200) {
      // 生成成功后重新加载推荐数据
      await loadRecommendations();
      ElMessage.success('推荐已重新生成');
    } else {
      ElMessage.error('生成推荐失败: ' + (generateResponse.msg || '未知错误'));
    }
  } catch (error) {
    console.error('生成推荐失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 监听用户ID变化
watch(() => props.currentUserId, (newUserId) => {
  if (newUserId) {
    loadRecommendations()
  }
})

// Initialize
onMounted(() => {
  // 直接调用loadRecommendations，函数内部会检查用户ID是否有效
  loadRecommendations();
})

// Expose methods for parent component
defineExpose({
  loadRecommendations,
  refreshRecommendations,
  generateRecommendations
})
</script>

<style scoped>
.smart-recommendations {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h2 {
  margin: 0;
  color: #303133;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.recommendation-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.rec-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.rec-logo {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.rec-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.rec-info {
  flex: 1;
}

.rec-info h4 {
  margin: 0 0 4px;
  color: #303133;
}

.rec-info p {
  margin: 0 0 8px;
  color: #909399;
  font-size: 14px;
}

.match-score {
  text-align: center;
  flex-shrink: 0;
}

.score-circle {
  background: #409eff;
  color: white;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 auto 4px;
}

.score-number {
  font-size: 16px;
  font-weight: bold;
}

.score-label {
  font-size: 10px;
}

.score-desc {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.rec-details {
  margin-bottom: 16px;
}

.rec-details h5 {
  margin: 0 0 8px;
  color: #303133;
  font-size: 14px;
}

.score-breakdown {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.score-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score-item span:first-child {
  width: 80px;
  font-size: 12px;
  color: #606266;
}

.score-item span:last-child {
  width: 40px;
  text-align: right;
  font-size: 12px;
  color: #409eff;
  font-weight: 500;
}

.rec-recommendation {
  margin-bottom: 16px;
}

.rec-recommendation h5 {
  margin: 0 0 8px;
  color: #303133;
  font-size: 14px;
}

.rec-recommendation p {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.rec-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.club-detail-dialog .club-detail {
  padding: 10px 0;
}

.club-detail-dialog .club-detail-logo {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  margin: 0 auto;
}

.club-detail-dialog .club-detail-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.club-detail-dialog .club-detail-info {
  padding: 10px 0;
}

.club-detail-dialog .club-detail-info h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

/* 调试面板样式 */
.debug-panel {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
}

.debug-panel h3 {
  margin-top: 0;
  color: #409eff;
  font-size: 18px;
}

.debug-panel h4 {
  margin-top: 15px;
  margin-bottom: 10px;
  color: #606266;
  font-size: 16px;
}

.debug-panel pre {
  background-color: #303133;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
}

.debug-panel code {
  background-color: #f0f2f5;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  color: #e74c3c;
}

.debug-field {
  padding: 5px 0;
  border-bottom: 1px dotted #e4e7ed;
  font-size: 14px;
}

.debug-field strong {
  color: #606266;
}
</style>
